package com.tmall.testgen.common.socket;

import java.io.EOFException;
import java.net.Socket;

/**
 * @author haojia
 * @date 2014-07-04
 */
public class SocketInfoListener  {

	
	 private  Socket socket;
	 private Object socketSyn;
	 private ReceiveObjectHandler receiveObjectHandler;
	 
	public  SocketInfoListener( Socket socket,Object socketSyn,ReceiveObjectHandler receiveObjectHandler){
		 this.socket=socket;
		 this.socketSyn=socketSyn;
		 this.receiveObjectHandler=receiveObjectHandler;
	 }
	 public void startListener( ){
		 new Thread(new InnerRunnable() ).start();
	 }
	class InnerRunnable implements Runnable{
		@Override
		public void run() {
			
			while(!socket.isClosed()){
				try {
					//System.out.println("等待读取");
					Object receiveObj=TransferHandler.readObject(socket.getInputStream());// in.readObject();
					
					receiveObjectHandler.handleReceiveObj(receiveObj);
				} catch (Exception e1) {
				    
					try {
						System.out.println("进入关闭");
						socket.close();
						
						if(socketSyn!=null){
							synchronized (socketSyn) {
								System.out.println("释放锁定");
								socketSyn.notifyAll();
							}
						}
//						StringWriter sw = new StringWriter();  
//	                    PrintWriter pw = new PrintWriter(sw);  
//	                    e1.printStackTrace(pw);  
//	                    
//						e1.printStackTrace();
						
					} catch (Exception e) {
					    if(!(e instanceof EOFException))
					        e.printStackTrace();
					}
			}
				
			} 
			
		}
	}
	public Socket getSocket() {
		return socket;
	}
	public void setSocket(Socket socket) {
		this.socket = socket;
	}
	public ReceiveObjectHandler getReceiveObjectHandler() {
		return receiveObjectHandler;
	}
	public void setReceiveObjectHandler(ReceiveObjectHandler receiveObjectHandler) {
		this.receiveObjectHandler = receiveObjectHandler;
	}
	
	
	

}
